<?php

namespace Endor\EndorBundle\Model;

class InventarioModel {
    private $Connection;
    
    function __construct($Connection) {
        $this->Connection = $Connection;
    }
    
    public function GetByBodega($IdBodega) {
        
        $result = $this->Connection->createQueryBuilder()->select("*")->from("stocks_bodegas", "sb")->where("id_bodega = ".$IdBodega)->execute()->fetchAll();
        
        return $result;
    }
    
    public function GetByBodegaArticulo($IdBodega, $IdArticulo) {
        
        $result = $this->Connection->createQueryBuilder()->select("*")->from("stocks_bodegas", "sb")->where("id_bodega = ".$IdBodega." and id_articulo = ".$IdArticulo)->execute()->fetchAll();
        
        return $result;
    }
    
     public function Get() {
        $Query = "SELECT * FROM endor.stocks_articulos as StocksArticulos";
        $result = $this->Connection->executeQuery($Query)->fetchAll();
        return $result;
    }
    
    public function GetCantidadEntradas($idEntrada) {
        $result = $this->Connection->createQueryBuilder()->select("Cantidad")->from("endor.stock_entradas", "stock")->where("id_entrada = ".$idEntrada)->execute()->fetchAll();
        return $result;
    }
    
    public function GetDisponible($cantidad, $bodega, $articulo) {
        $Query = "   
        set @cant = ". $cantidad .";
        set @bodega = ". $bodega .";
        set @articulo = ". $articulo .";
        set @cantidad = (select case when sum(entradas.cantidad) is not null then sum(entradas.cantidad) else 0 end -
               case when sum(salidas.cantidad) is not null then sum(salidas.cantidad) else 0 end cantidad 
        from endor.entradas left outer join endor.salidas on
            endor.entradas.id_articulo = endor.salidas.id_articulo and 
            endor.entradas.id_bodega = endor.salidas.id_bodega
        where entradas.id_articulo = @articulo and entradas.id_bodega = @bodega);

        select case when id_stock is not null then 
            case when @dis<=0 then 0 else
                    case when min < @dis + @cant and max > @dis + @cant then 1 else 0 end
                end
            else 1 end IsValid
        from endor.stocks
        where id_articulo = @articulo and id_bodega = @bodega;
";
        $result = $this->Connection->executeQuery($Query)->fetchAll();
        
        $result = $result[0];
        $result = $result["IsValid"];
        
        return $result;
    }
}

?>
